//
//  RequestViewController.m
//  WeiMo
//
//  Created by weixian he on 12-9-16.
//  Copyright (c) 2012年 . All rights reserved.
//

#import "RequestViewController.h"

#import <QuartzCore/QuartzCore.h>

#import "DateInputTableViewCell.h"
#import "TextFieldTableViewCell.h"

#import "FMManager.h"
#import "InterfaceDefine.h"
#import "JSONKit.h"

#define kTextFieldTagBase (100)
@interface RequestViewController ()
{
    MBProgressHUD *mHUD;
}
@property(nonatomic,retain) NSMutableArray *cellTexts;
@property(nonatomic,retain) NSMutableArray* textFields;
@property (nonatomic,copy) NSString *publishProvinceId;
@property (nonatomic,copy) NSString *publishCityId;
@end

@implementation RequestViewController
@synthesize inputList;
@synthesize textFields = _textFields;
@synthesize cellTexts = _cellTexts;
@synthesize delegate;
@synthesize publishCityId,publishProvinceId;

-(void)dealloc
{
    self.delegate = nil;
    self.inputList = nil;
    self.textFields = nil;
    self.cellTexts = nil;
    self.publishCityId =nil;
    self.publishProvinceId = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor colorWithRed:231/255.0 green:232/255.0 blue:238/255.0 alpha:1.0];
    
    self.publishProvinceId = @"";
    self.publishCityId = @"";
    
    self.title = @"发布通告";
    self.inputList = [[[NSMutableArray alloc] init]autorelease];
    self.cellTexts= [[[NSMutableArray alloc] init] autorelease];
    [self.cellTexts addObject:@"地点:"];
//    [self.cellTexts addObject:@"时间:"];
    [self.cellTexts addObject:@"工作:"];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStyleDone target:self action:@selector(publishMessages)];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    [rightButtonItem release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self hideRequestTabBar];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - private

//隐藏TabBar
- (void)hideRequestTabBar
{
    if (self.tabBarController.tabBar.hidden == YES)
    {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
}

//发布公告
-(void)publishMessages
{
    if(self.inputList.count > 0)
    {
        ChinaCityChooseCell *cell1 = [self.inputList objectAtIndex:0];
        NSString *city = cell1.detailTextLabel.text;
        if (!city || [city isEqualToString:@""])
        {
            [FMManager showAlertView:@"请选择工作地点!"];
            return;
        }
        
        TextFieldTableViewCell *cell3 = [self.inputList objectAtIndex:1];
        NSString *job = cell3.textField.text;
        if(!job || [job isEqualToString:@""])
        {
            [FMManager showAlertView:@"请填写工作内容!"];
            return;
        }
    
        NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kInsertJob];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        FMManager *fm =[FMManager sharedInstance];
        NSString *userType = fm.modeIdentify;
        [dic setObject:fm.userId forKey:@"userId"];
        [dic setObject:job forKey:@"jobsInformation"];
        [dic setObject:self.publishCityId forKey:@"cityid"];
        [dic setObject:self.publishProvinceId forKey:@"provinceid"];
        [dic setObject:userType forKey:@"userType"];
        [dic setObject:@"" forKey:@"endTime"];
        
        NSString *postStr = [dic JSONString];
        [dic release];
            
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
        [request setRequestMethod:@"POST"];
        request.delegate = self;
        [request startAsynchronous];
            
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.cellTexts.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int section = indexPath.section;
    if(section == (self.cellTexts.count - 1))
    {
        return 140;
    }
    
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int section = indexPath.section;
    
    if (section == 0)
    {
        static NSString *publishCityCell = @"publishCityCell";
        ChinaCityChooseCell *cell = [tableView dequeueReusableCellWithIdentifier:publishCityCell];
        if(cell == nil)
        {
            cell = [[[ChinaCityChooseCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:publishCityCell] autorelease];
            cell.delegate = self;
            [self.inputList addObject:cell];
        }
        
        cell.textLabel.text = @"活动城市:";
        
        return cell;
    }
//    else if (section == 1)
//    {
//        static NSString *publishDateCell = @"publishDateCell";
//        DateInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:publishDateCell];
//        if(cell == nil)
//        {
//            cell = [[[DateInputTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:publishDateCell] autorelease];
//            [cell setMinDate:[NSDate date]];
//            cell.textLabel.textColor = [UIColor lightGrayColor];
//            cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            [self.inputList addObject:cell];
//        }
//        
//        cell.textLabel.text = @"活动日期:";
//        
//        return cell;
//    }
    else
    {
        static NSString *publishContentCell = @"publishContentCell";
        TextFieldTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:publishContentCell];
        if(cell == nil)
        {
            cell = [[[TextFieldTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:publishContentCell] autorelease];
            cell.textLabel.textColor = [UIColor lightGrayColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [self.inputList addObject:cell];
        }
        
        return cell;
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - ChinaCityChooseCellDelegate

- (void)returnChoosedChinaCityWithProvinceId:(NSString *)provinceId andCityId:(NSString *)cityId
{
    self.publishProvinceId = provinceId;
    self.publishCityId = cityId;
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    if(array == nil || array.count == 0)
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"发布失败";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
    
    NSString *item0 = [array objectAtIndex:0];
    if(![item0 isEqualToString:kResponseOk])
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"发布失败";
        [mHUD hide:YES afterDelay:1.5];
        return;
    }
    else
    {
        if(mHUD == nil)
        {
            mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:mHUD];
            mHUD.delegate = self;
            [mHUD show:YES];
        }
        mHUD.mode =MBProgressHUDModeText;
        mHUD.labelText = @"发布成功";
        [mHUD hide:YES afterDelay:1];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    if (error)
    {
        NSLog(@"error = %@",error);
    }
    
    if(mHUD == nil)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
    mHUD.mode =MBProgressHUDModeText;
    mHUD.labelText = @"网络链接失败";
    [mHUD hide:YES afterDelay:1.5];
}

#pragma mark - MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
    
    if([mHUD.labelText isEqualToString:@"发布成功"])
    {
        if(self.delegate)
        {
            [self.delegate comiOK];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}

@end